import React, { useState,useEffect,useRef} from 'react'
import { CarOutlined, DeleteOutlined } from '@ant-design/icons';
import { Input, Select, DatePicker, Space, Pagination, Card, Form, Modal, message, Popconfirm } from 'antd';
import { plateColor, carGroup, carPoint } from '@/assets/data/common.js'
import { getCarApi, pagGetCarApi, addCarApi, CarSearchApi, carGroupSearchApi, deleteCraApi } from '@/request/datamanagment.js'
import { addUserLoginApi } from '@/request/logmanagment.js'
import cookie from 'react-cookies';
import carImg from '@/assets/img/car.jpg'
import '@/assets/less/datamanagment.less'
import { ImgUpload, CarInfo, ExcelExport } from '@/component/index';
import GroupShow from './GroupShow'
import moment from 'moment'
import locale from 'antd/lib/date-picker/locale/zh_CN'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
function DataManagment() {
  const [carData, setCarData] = useState([]);
  const [dataTatal, setDataTatal] = useState([]);
  const [addCarImg, setAddCarImg] = useState([]);                  //添加车辆图片
  const [addDataVisible, setAddDataVisible] = useState(false)
  const [isshowAllCarInfo, setshowAllCarInfo] = useState("none")   //显示大图
  const [AllCarInfo, setAllCarInfo] = useState()                   //大图数据
  const [isGroupShow, setIsGroupShow] = useState(false)            //是否分组显示
  const [groupData, setGroupData] = useState([])                   //是否分组显示
  const [showExcel, setShowExcel] = useState(false)                //显示excel导出框
  const [dataLoad,  setDataLoad] = useState(false)                //判断数据是否加载完成,是否隐藏分页框
  const [isSearch,  setIsSearch] = useState(false)                //判断是否处于搜索状态
  const [searchData, setSearchData] = useState([])              
  const [pagination, setPagination] = useState({ current: 1, pageSize: 12, total: 0 })
  const [form] = Form.useForm();  

  let searchRef =useRef({
    plate_number:"",  //车牌号
    plate_color:"",   //车牌颜色
    startTime:"",     //起始时间
    endTime:""        //终止时间
  })

  /* 日志参数 */
  const logparams = useRef({
    id: '',
    username: "",
    function_module: "",
    search_condation: "",
    handle: ""
  })
  
  let uploadProps = {
    count:1,
    message:"点击上传车辆图片",
    upload:(value)=>setAddCarImg(value)
  }

  /* 获取用户信息 */
  let userInfo = cookie.load("userInfo")
  useEffect(()=>{
    logparams.current.id = userInfo.id
    logparams.current.username = userInfo.username
    getCartotal()
    getCarData(pagination.current, pagination.pageSize)
  },[])

  /* 获取车辆总数*/
  const getCartotal = ()=>{
    getCarApi().then(res => setDataTatal(res.data.length))
  }
  //获取展示
  const getCarData = (current, pageSize)=>{
    setPagination({ current, pageSize, total: dataTatal })
    pagGetCarApi(current, pageSize).then(res => {
      setCarData(res.data)
      setTimeout(() =>setDataLoad(true), 0);
    })
  }


  // 添加数据
  const addhandleOk=()=>{
    let carInfo = Object.assign({},form.getFieldsValue(), { "vehicle_img": addCarImg })
    addCarApi(carInfo).then(res=>{
      message.success(res.message)
      setAddDataVisible(false)
      logRecord("","添加车辆数据");
    })
  }

  const cancelhandle = ()=>{
    setAddDataVisible(false)
    form.resetFields();  //重置表单
  }


  //获取录入时间
  const onChangeTime = (value, dateString) => {
    console.log(dateString);
    form.setFieldValue("entry_time", dateString )
  };

  // 查询详细详细
  const showAllCarInfo=(value)=>{
    let showCarInfo = {
      carInfo: value,
      currentPageInfo: carData,
    }
    setAllCarInfo(showCarInfo)
    setshowAllCarInfo("block")
  }

  // 车辆范围搜索查询
  const getPlateNumber=(event)=>{
    searchRef.current = { ...searchRef.current, plate_number:event.target.value };
  }
  const getPlateColor = (value) => searchRef.current = { ...searchRef.current, plate_color: value };
  const starttimehandle = (value, dateString)=>{
    searchRef.current = { ...searchRef.current, startTime: new Date(dateString).format("yyyy-MM-dd hh:mm:ss") };
  }
  const endTimeHandle = (_, dateString)=>{
    searchRef.current = { ...searchRef.current, endTime: new Date(dateString).format("yyyy-MM-dd hh:mm:ss") };
  }

  const carSearch=()=>{
    if (searchRef.current.startTime === "" || searchRef.current.endTime === ""){
     return message.warn("请输入完整的录入时间范围")
    }

    
    CarSearchApi(searchRef.current).then(res=>{
      setIsSearch(true)
      setSearchData(res.data)
      setCarData(res.data.slice(0,12)) 
      setDataTatal(res.data.length)
      let str = `车牌号:${searchRef.current.plate_number}
                车牌颜色:${searchRef.current.plate_color}
                起始时间:${searchRef.current.startTime}
                结束时间：${searchRef.current.endTime}`
      logRecord(str,"精确搜索")
    })
  }

  /* 车辆分组查询 */
  const groupChangeHandler =(value)=>{
    carGroupSearchApi(value).then(res=>{
     if (res.code===0) {   //不分组
       setCarData(res.data)
       setIsGroupShow(false)
       setDataLoad(true)
     }else{
       setDataLoad(false)
       setIsGroupShow(true)
       setGroupData({
         group: res.group,
         data: res.data
       })
       logRecord(value,"车辆分组查询")
     }
    })
  }
  const paginationHandle = (current, pageSize) => {
    if (!isSearch){
      getCarData(current, pageSize)
    }else{
      let data = searchData.slice((current - 1) * pageSize, pageSize * current)
      console.log(data);
      setCarData(data)
      setPagination({ current, pageSize, total: dataTatal })
    }
  }

  /* 删除 */
  const deletecarHandler=(id)=>{
    deleteCraApi(id).then(res=>{
      if(res.code){
        getCarData(pagination.current, pagination.pageSize)
        setDataTatal(dataTatal-1)
      }
    })
  }

  /* 日志记录 */
  const logRecord = (search, handle) => {
    logparams.current = {
      ...logparams.current,
      function_module: localStorage.getItem("pathname"),
      search_condation: search,
      handle: handle
    }
    addUserLoginApi(logparams.current).then(res => { })
  }


  return (
    <div className='datamanagment'>
      <div className='head_search'>
        <div className='head_search_left'> 
          <p>车牌号 <Input size="middle" style={{ "width": "150px" }} placeholder="请输入车牌号" prefix={<CarOutlined />} onChange={getPlateNumber} /></p>
          <p>车牌颜色  <Select defaultValue="不限" showArrow options={plateColor} onChange={getPlateColor}/></p>
          <p>录入时间  <Space direction="vertical" size={12}> 
            <DatePicker showTime onChange={starttimehandle} placeholder="请输入起始时间" format={"YYYY-MM-DD HH:mm"} locale={locale} 
            />
          </Space></p>
          <p>至 
            <Space direction="vertical" size={12}>
              <DatePicker showTime onChange={endTimeHandle} placeholder="请输入终止时间" format={"YYYY-MM-DD HH:mm"} locale={locale} />
            </Space>
            </p></div>
        <div className='head_search_right'>
          <div className="button-wrapper" onClick={carSearch}>检索</div>
          <span className='line'></span>
          <div className="button-wrapper" onClick={() => setAddDataVisible(true)}>点击添加数据</div>
          <span className='line'></span>
          <div className="button-wrapper" onClick={() => setShowExcel(true)}>导出execl</div>
          <ExcelExport 
                    carData={carData} 
                    isShowExport={(value) => setShowExcel(value)} 
                    showExcel={showExcel} 
                    pagination={pagination}
                    logRecord={logRecord}
                    />
        </div> 
      </div>
      <div className='group_export'>
        <div className='group_export_left'>
          <span className='search_result'>共找到{dataTatal}条结果,用时0.5s</span>
          <Select
            defaultValue="不限"
            showArrow
            options={carGroup}
            style={{ "width": "200px" }}
            onChange={groupChangeHandler}
          />
        </div>
      </div>
      <div className='data_content'>
        {
          isGroupShow ? 
            <GroupShow {...groupData}></GroupShow> :
            carData.map((item, index) => {
              return (
                <div className='data_content_item' key={index}>
                  <Card
                    bodyStyle={{ height: "130px", background: "rgb(241, 240, 240)", boxSizing: 'border-box' }}
                    cover={<img src={item.vehicle_img || carImg} title="点击图片查看详细详细" onClick={() => showAllCarInfo(item)} />}
                  >

                    <div className='car_info'>
                      <p>{item.plate_number}</p>
                      <p>{item.vehicle_type}</p>
                      <p>{item.entry_time}</p>
                      <p>测试点位{item.point}</p>
                      <p>
                        <Popconfirm title="确认删除?" okText="Yes" cancelText="No" onConfirm={() => deletecarHandler(item.id)}>
                          <DeleteOutlined key="delete" style={{ fontSize: 20 }} />
                        </Popconfirm>
                      </p>
                    </div>
                  </Card>
                </div>
            )
          })
        }
       
      </div>
      <div className='pagination'>
        {
          dataLoad ? <Pagination
            total={dataTatal}
            showQuickJumper={true}
            showTotal={(total) => `共 ${total} 条数据`}
            defaultPageSize={12}
            defaultCurrent={1}
            onChange={paginationHandle}
            hideOnSinglePage={true}
            pageSizeOptions={[12, 24, 36, 48]}
          /> :""
        }
      </div>
      <Modal title="添加车辆数据" visible={addDataVisible} onOk={addhandleOk}
        onCancel={cancelhandle}
        okText="提交"
        cancelText
        width={500}
      >
        <div style={{ width: "350px" }}>
          <Form
            form={form}
            name="basic"
            style={{width:"300px"}}
          >
            <Form.Item
              //隐藏该字段 
              hidden='true'
              label="车辆id"
              name="id"
            >
              <Input  />
            </Form.Item>
            <Form.Item
              label="车辆点位"
              name="point"
              labelCol={{ span: 6, offset: -1 }}

            >
              <Select
                showArrow
                placeholder="请选择点位"
                listHeight={100}
                options={carPoint}
                style={{ width: "150px" }} 
              />
            </Form.Item>
          <Form.Item
            label="车辆颜色"
            name="vehicle_color"
            labelCol={{ span: 6, offset: -1 }}

          >
            <Select
              showArrow
              placeholder="请选择颜色"
              listHeight={100}
              options={plateColor}
              style={{ width: "150px" }}
            />
          </Form.Item>
          <Form.Item
            label="录入时间"
            name="entry_time"
            labelCol={{ span: 6, offset: -1 }}

          >
            <Space direction="vertical" size={12}>
              <DatePicker showTime onChange={onChangeTime}  placeholder="请输入起始时间"
                style={{ width: "150px" }}/>
            </Space>
          </Form.Item>

          <Form.Item
            label="车牌号码"
            name="plate_number"
            labelCol={{ span: 6, offset: -1 }}

          >
          <Input style={{ width: "150px" }} />
          </Form.Item>
          </Form>
        </div>
        <div id='car_img' >
        <ImgUpload {...uploadProps}></ImgUpload>
        </div>
      </Modal>
      {
        isshowAllCarInfo === "block" ? <div className='showAllCarInfo' style={{ display: (isshowAllCarInfo), transition: "all 0.1s ease"}}>
          <CarInfo
            {...AllCarInfo}
            isShow={(v) => setshowAllCarInfo(v)}
          ></CarInfo>
        </div>:""
      }
    </div>
  )
}

export default DataManagment
